<template>
  <header class="min-w-full text-gray-600">
    <div
      class="container mx-auto flex flex-col flex-wrap items-center px-5 py-3 shadow-md md:flex-row"
    >
      <a
        class="mb-4 flex items-center font-medium text-gray-900 md:mb-0"
        :href="metadata.website"
        target="_blank"
      >
        <img
          src="/logo.png"
          class="h-10"
          alt="logo"
        />
        <span class="ml-3 text-xl">sql-tools</span>
      </a>
      <nav
        class="flex flex-wrap items-center justify-center space-x-2 text-base md:ml-4 md:mr-auto md:border-l md:border-gray-400 md:py-1 md:pl-4"
      >
        <Select
          v-model:value="parseMode"
          class="parse-mode-select"
          :options="[
            { value: 'noMatedata', label: '无元数据' },
            { value: 'external', label: '外部元数据' }
          ]"
        />
        <div>
          <label v-show="parseMode === 'noMatedata'" for="dbTypeSelect">数据库类型：</label>
          <Select
            v-show="parseMode === 'noMatedata'"
            v-model:value="selectedValue"
            class="db-type-select"
            @change="handleChange"
            :loading="!dbTypeOptions.length"
            :options="dbTypeOptions"
            id="dbTypeSelect"
          />
        </div>
        
        <template v-if="parseMode === 'external'">
          <label for="dbTypeSelect">Matelake：</label>
          <Select
            v-model:value="selectedMatelake"
            class="external-select"
            :options="matelakeOptions"
            :loading="matelakeLoading"
            placeholder="选择Matelake"
            style="width: 80px; margin-right: 12px;"
            @change="handleMatelakeChange"
          />
          <label for="dbTypeSelect">Catalog：</label>
          <Select
            v-model:value="selectedCatalog"
            class="external-select"
            :options="catalogOptions"
            :loading="catalogLoading"
            placeholder="选择Catalog"
            :disabled="!selectedMatelake"
            style="width: 100px; margin-right: 12px;"
          />
        </template>
        <div v-show="parseMode !== 'external'" class="create-table-switch">
          <Tooltip placement="bottom" title="使用建表语句获取表信息">
            <Switch v-model:checked="isCreateTable" size="small" />
          </Tooltip>
        </div>
        <Input
          v-model:value="columnName"
          placeholder="字段段名"
          style="width: 150px"
          @keyup.enter="handleParseSql"
        />
        <Tooltip placement="bottom" title="解析血缘">
          <Button
            type="primary"
            class="bg-[#1677ff]"
            :style="{
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              padding: '4px 8px'
            }"
            @click="handleParseSql"
          >
            <RocketOutlined />
          </Button>
        </Tooltip>
      </nav>
      <!-- 搜索框和设置按钮放在一起 -->
      <div class="flex items-center gap-2 ml-auto">
        <Setting v-model:open="open">
          <template #default>
            <Form
              :label-col="{ span: 24 }"
              :wrapper-col="{ span: 24 }"
              class="settings-form"
              @submit.prevent="handleSaveSettings"
            >
              <FormItem>
                <div class="flex items-center mb-4">
                  <label class="w-24 text-right mr-4 text-gray-600">主&nbsp;&nbsp;&nbsp;题：</label>
                  <Select
                    class="flex-1"
                    v-model:value="localTheme"
                    :defaultValue="localTheme"
                    :options="[
                      { value: 'vs-light', label: 'Light' },
                      { value: 'vs-dark', label: 'Dark' },
                      { value: 'vs-eyecare', label: 'Eyecare' }
                    ]"
                  />
                </div>
              </FormItem>
              <FormItem>
                <div class="flex items-center mb-4">
                  <label class="w-24 text-right mr-4 text-gray-600">水&nbsp;&nbsp;&nbsp;印：</label>
                  <Input
                    class="flex-1"
                    v-model:value="localTextWaterMarker"
                  />
                </div>
              </FormItem>
              <!-- 高亮颜色设置已移除 -->
              <FormItem>
                <div class="flex items-center mb-4">
                  <label class="w-24 text-right mr-4 text-gray-600">缩略图：</label>
                  <div class="flex-1">
                    <Switch
                      v-model:checked="localShowMinimap"
                      class="custom-switch"
                    />
                  </div>
                </div>
              </FormItem>
              <FormItem>
                <div class="border-t pt-6 mt-2">
                  <Button
                    type="primary"
                    html-type="submit"
                    class="w-full custom-save-button"
                    :loading="loading"
                  >
                    保存设置
                  </Button>
                </div>
              </FormItem>
            </Form>
          </template>
        </Setting>
      </div>

      <div
        class="ml-2 hidden items-center rounded-md shadow-sm ring-1 ring-gray-900/5 lg:flex"
      >
        <HeaderButton
          :isActive="layout === 'vertical'"
          label="Switch to vertical split layout"
          @click="$emit('layoutChange', 'vertical')"
        >
          <path
            d="M12 3h9a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-9"
            fill="none"
          />
          <path
            d="M3 17V5a2 2 0 0 1 2-2h7a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H5a2 2 0 0 1-2-2Z"
          />
        </HeaderButton>
        <HeaderButton
          :isActive="layout === 'editor'"
          label="Switch to preview-only layout"
          @click="$emit('layoutChange', 'editor')"
        >
          <path
            fill="none"
            d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
          />
        </HeaderButton>
        <HeaderButton
          :isActive="layout === 'preview'"
          label="Switch to preview-only layout"
          @click="$emit('layoutChange', 'preview')"
        >
          <path
            d="M23 17V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2Z"
            fill="none"
          />
        </HeaderButton>
      </div>
    </div>
  </header>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import metadata from '../../config/metadata';
import HeaderButton from './headerButton.vue';
import Setting from './setting.vue';
import { Button, Form, Input, Select, Switch, Tooltip } from 'ant-design-vue';
const FormItem = Form.Item;
import { RocketOutlined } from '@ant-design/icons-vue';
// ColorPicker 组件已不再使用
import { getDbTypes, getMatelakes, getCatalogs } from '../../services/api';

interface HeaderProps {
  /** 列名 */
  columnName?: string;
  /** 编辑器主题色 */
  theme: string;
  /** 布局方式 */
  layout: string;
  /** 水印文字 */
  textWaterMarker: string;
  // 高亮颜色设置已移除
  /** 是否显示缩略图 */
  showMinimap: boolean;
  /** 是否为创建表操作 */
  isCreateTable: boolean;
}

// 使用props中的columnName初始值
const columnName = computed({
  get: () => props.columnName || '',
  set: (val) => emit('update:columnName', val)
});
const props = defineProps<HeaderProps>();
const emit = defineEmits([
  'themeChange',
  'layoutChange',
  'handleParseSql',
  'update:columnName',
  // 高亮颜色事件已移除
  'textWaterMarkerChange',
  'dbTypeChange',
  'update:showMinimap',
  'update:isCreateTable',
  'parseModeChange',
  'update:selectedMatelake',
  'update:selectedCatalog',
]);
const open = ref(false);
const parseMode = ref('noMatedata'); // 默认为解析sql语句
const selectedValue = ref('');
const selectedMatelake = ref('');
const selectedCatalog = ref('');
const matelakeOptions = ref<{value: string; label: string}[]>([]);
const catalogOptions = ref<{value: string; label: string}[]>([]);
const matelakeLoading = ref(false);
const catalogLoading = ref(false);

// 获取matelakes数据
const fetchMatelakes = async () => {
  matelakeLoading.value = true;
  try {
    const response = await getMatelakes();
    
    // 直接使用响应数组，假设接口返回的就是数组
    matelakeOptions.value = response.map(item => ({
      value: String(item),
      label: String(item)
    }));
  } catch (error) {
    console.error('Failed to fetch matelakes:', error);
    matelakeOptions.value = [];
  } finally {
    matelakeLoading.value = false;
  }
};

// 获取catalogs数据
const fetchCatalogs = async (matelake: string) => {
  catalogLoading.value = true;
  try {
    // 确保参数名称与API函数中的一致
    const response = await getCatalogs(matelake);
    
    // 检查响应格式
    if (response && response.data) {
      catalogOptions.value = response.data.map(item => ({
        value: String(item),
        label: String(item)
      }));
    } else if (Array.isArray(response)) {
      catalogOptions.value = response.map(item => ({
        value: String(item),
        label: String(item)
      }));
    } else {
      console.warn('Unexpected catalogs response format:', response);
      catalogOptions.value = [];
    }
  } catch (error) {
    console.error('Failed to fetch catalogs:', error);
    // 添加更详细的错误日志
    if (error.response) {
      // 服务器响应了，但状态码不在2xx范围内
      console.error('Error response data:', error.response.data);
      console.error('Error response status:', error.response.status);
      console.error('Error response headers:', error.response.headers);
    } else if (error.request) {
      // 请求已发送，但没有收到响应
      console.error('No response received:', error.request);
    } else {
      // 设置请求时发生了错误
      console.error('Request error:', error.message);
    }
    catalogOptions.value = [];
  } finally {
    catalogLoading.value = false;
  }
};

// 监听解析模式变化
watch(parseMode, async (newMode) => {
  if (newMode === 'external') {
    isCreateTable.value = false;
    await fetchMatelakes();
  } else {
    // 清空外部元数据相关选择
    selectedMatelake.value = '';
    selectedCatalog.value = '';
    matelakeOptions.value = [];
    catalogOptions.value = [];
  }
  emit('parseModeChange', newMode);
});

// 处理matelake选择变化
const handleMatelakeChange = async (value: string) => {
  emit('update:selectedMatelake', value);
  selectedCatalog.value = '';
  catalogOptions.value = [];
  
  if (value) {
    await fetchCatalogs(value);
  }
};

// 监听matelake选择变化
watch(selectedMatelake, (newMatelake) => {
  emit('update:selectedMatelake', newMatelake);
});

// 监听catalog选择变化
watch(selectedCatalog, (newCatalog) => {
  emit('update:selectedCatalog', newCatalog);
});

const dbTypeOptions = ref<{ value: string; label: string; }[]>([]);
// 使用computed的完整形式，包含getter和setter
const theme = computed({
  get: () => props.theme,
  set: (val) => {
    // 本地更新值，但不立即触发事件，等待保存按钮点击
    localTheme.value = val;
  }
});

const textWaterMarker = computed({
  get: () => props.textWaterMarker,
  set: (val) => {
    // 本地更新值，但不立即触发事件，等待保存按钮点击
    localTextWaterMarker.value = val;
  }
});

// 高亮颜色相关计算属性已移除

// 本地状态变量，用于临时存储修改但尚未保存的值
const localTheme = ref(props.theme);
const localTextWaterMarker = ref(props.textWaterMarker);
// 本地高亮颜色变量已移除
const localShowMinimap = ref(props.showMinimap);
const isCreateTable = computed({
  get: () => props.isCreateTable,
  set: (val) => emit('update:isCreateTable', val)
});

// 获取数据库类型列表
const fetchDbTypes = async () => {
  try {
    const response = await getDbTypes();
    if (Array.isArray(response)) {
      dbTypeOptions.value = response.map(type => ({
        value: type,
        label: type
      }));
      // 设置默认选中值
      if (dbTypeOptions.value.length > 0) {
        selectedValue.value = dbTypeOptions.value[0].value;
      }
    }
  } catch (error) {
    console.error('Failed to fetch database types:', error);
  }
};

// 组件挂载时获取数据库类型
onMounted(() => {
  fetchDbTypes().then(() => {
    // 确保在获取到数据库类型后，立即触发默认值的变更
    if (selectedValue.value) {
      emit('dbTypeChange', selectedValue.value);
    }
  });
  
  // 如果初始模式是外部元数据，加载matelakes
  if (parseMode.value === 'external') {
    fetchMatelakes();
  }
});

const handleChange = (value: string) => {
  emit('dbTypeChange', value);
};

const handleParseSql = () => {
  emit('handleParseSql');
  emit('update:columnName', columnName.value);
};

const handleSaveSettings = () => {
  // 保存主题设置
  emit('themeChange', localTheme.value);

  // 保存水印文字设置
  emit('textWaterMarkerChange', localTextWaterMarker.value);

  // 高亮颜色保存已移除

  // 保存缩略图显示设置
  emit('update:showMinimap', localShowMinimap.value);

  // 关闭设置面板
  open.value = false;
};

const setTheme = (value: string) => {
  //   props.setTheme(value);
  emit('themeChange', value);
};

const setTextWaterMarker = (text: string) => {
  //   props.setTextWaterMarker(text);
  emit('textWaterMarkerChange', text);
};

// 设置高亮颜色方法已移除
</script>

<style scoped>
.parse-mode-select {
  width: 140px;
  margin-right: 12px;
}

.parse-mode-select :deep(.ant-select-selector) {
  height: 32px !important;
  padding: 0 11px !important;
}

.parse-mode-select :deep(.ant-select-selection-item) {
  line-height: 30px !important;
  font-size: 14px;
}

.external-select {
  width: 50px;
  margin-right: 12px;
}

.external-select :deep(.ant-select-selector) {
  height: 32px !important;
  padding: 0 11px !important;
}

.external-select :deep(.ant-select-selection-item) {
  line-height: 30px !important;
  font-size: 14px;
}

.db-type-select {
  width: 100px;
  margin-right: 12px;
}

.db-type-select :deep(.ant-select-selector) {
  height: 32px !important;
  padding: 0 11px !important;
}

.db-type-select :deep(.ant-select-selection-item) {
  line-height: 30px !important;
  font-size: 14px;
}

.create-table-switch {
  display: inline-flex;
  align-items: center;
  margin-right: 12px;
  cursor: pointer;
}

/* 优化开关样式 */
.create-table-switch :deep(.ant-switch) {
  min-width: 28px;
  height: 16px;
  background-color: rgba(0, 0, 0, 0.25);
}

.create-table-switch :deep(.ant-switch-checked) {
  background-color: #1890ff;
}

.create-table-switch :deep(.ant-switch-handle) {
  width: 12px;
  height: 12px;
  top: 2px;
}

.create-table-switch :deep(.ant-switch-checked .ant-switch-handle) {
  left: calc(100% - 14px);
}

.create-table-switch :deep(.ant-switch:not(.ant-switch-checked) .ant-switch-handle) {
  left: 2px;
}

/* 添加悬停效果 */
.create-table-switch:hover :deep(.ant-switch:not(.ant-switch-checked)) {
  background-color: rgba(0, 0, 0, 0.45);
}

.create-table-switch:hover :deep(.ant-switch-checked) {
  background-color: #40a9ff;
}

/* 添加过渡效果 */
.create-table-switch :deep(.ant-switch),
.create-table-switch :deep(.ant-switch-handle) {
  transition: all 0.2s ease-in-out;
}

.setting-label {
  display: inline-block;
  width: 70px;
  text-align: right;
}

/* 确保设置面板中的标签对齐 */
.settings-form :deep(.w-24) {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  min-width: 96px;
}
.settings-form {
  width: 100%;
  min-width: 420px;
  padding: 0 12px;
}

.custom-save-button {
  background-color: #1890ff !important;
  border-color: #1890ff !important;
  color: #ffffff !important;
}

.custom-save-button:hover {
  background-color: #40a9ff !important;
  border-color: #40a9ff !important;
}

.custom-save-button:active {
  background-color: #096dd9 !important;
  border-color: #096dd9 !important;
}

.settings-form :deep(.ant-form-item) {
  margin-bottom: 20px;
}

.settings-form :deep(.ant-form-item-label) {
  text-align: left;
  padding-bottom: 8px;
}

.settings-form :deep(.ant-form-item-control-input-content) {
  display: flex;
  align-items: center;
}

.settings-form :deep(.ant-form-item:last-child) {
  margin-bottom: 12px;
  margin-top: 40px;
}

.settings-form :deep(.ant-select),
.settings-form :deep(.ant-input) {
  width: 100%;
}

.settings-form :deep(.ant-form-item-control-input) {
  min-height: 32px;
}

.settings-form .flex {
  gap: 12px;
}

/* 调整标签和输入框的间距 */
.settings-form :deep(.ant-form-item-label) > label {
  height: 32px;
  padding-right: 16px;
}

/* 自定义开关颜色 */
:deep(.custom-switch.ant-switch) {
  background-color: rgba(0, 0, 0, 0.25) !important;
}

:deep(.custom-switch.ant-switch.ant-switch-checked) {
  background-color: #1890ff !important;
}
</style>